import React, { useEffect, useState } from "react";
import { Button, Table, Tag, Popconfirm} from "antd";
import axios from "axios";
import {
  DeleteOutlined,
  EditOutlined,
  UploadOutlined,
} from "@ant-design/icons";
import { useNavigate } from "react-router-dom";
export default function Draft() {
  const user = JSON.parse(localStorage.getItem("token"));
  const [dataSource, setDataSource] = useState([]);
  const navigate=useNavigate()
  //获取渲染数据
  useEffect(() => {
    const getRightList = async () => {
      const res = await axios.get(
        `http://localhost:3000/news?author=${user.username}&auditState=0&_expand=category`
      );
      setDataSource(res.data);
    };
    getRightList();
  }, []);

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      render: (id) => {
        return <b>{id}</b>;
      },
    },
    {
      title: "新闻标题",
      dataIndex: "title",
      render:(title,item)=>{
        return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
      }
    },
    {
      title: "作者",
      dataIndex: "author",
    },
    { 
      title: "新闻分类",
      dataIndex: "category",
      key: "category",
      render: (category) => {
        return <div>{category.title}</div>;
      },
    },
    {
      title: "操作",
      render: (item) => {
        // item就是当前行
        return (
          <>
            <Button
            // 更新按键
              icon={<EditOutlined color="blue" />}
              shape="circle"
              color="blue"
              onClick={()=>{
                navigate(`/news-manage/update/${item.id}`)
              }}
            ></Button>
            <Popconfirm
              title="确定删除吗？"
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                confirmDelete(item);
              }}
            >
              <Button icon={<DeleteOutlined />} shape="circle" danger></Button>
            </Popconfirm>
            <Button
              icon={<UploadOutlined color="blue" />}
              shape="circle"
              color="blue"
              onClick={()=>uploadNews(item)}
            ></Button>
          </>
        );
      },
    },
  ];
  const confirmDelete = (item) => {
    // 先删除前端状态
    setDataSource(dataSource.filter((data) => data.id !== item.id));
    //二级子项数据删除
    axios.delete(`http://localhost:3000/news/${item.id}`);
  };
  const uploadNews=(item)=>{
    axios.patch(`http://localhost:3000/news/${item.id}`,{auditState:1}).then(()=>{
      navigate('/audit-manage/list')
    })
  }
  return (
    <div>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 5,
        }}
        rowKey={(item) => item.id}
      />
    </div>
  );
}
